#include <opencv2/opencv.hpp>
#include <iostream>
#include "VideoSummary.h"

using namespace std;
using namespace cv;

VideoCapture vc("D:\\workshop\\video\\videoSummary\\20120427_17-10-36_new.avi");
int framePos = 1;
Point mousePosition;
vector<Point> polyPoints;
vector<vector<Point>> poly;
int np = 0;

void playVideo( int , void*)
{
	vc.set( CV_CAP_PROP_POS_FRAMES , framePos );
}


static void onMouse( int event, int x, int y, int,  void* )
{
	if ( event == CV_EVENT_LBUTTONDBLCLK && np<8 )
	{
		mousePosition = Point(x,y);
		polyPoints.push_back(mousePosition);
		np++;
	}
}


int main()
{
	int imgWidth = vc.get(CV_CAP_PROP_FRAME_WIDTH);
	int imgHeight = vc.get(CV_CAP_PROP_FRAME_HEIGHT);
	np=0;
	RNG rng(12345);
	BackgroundSubtractorMOG bsm;
	VideoWriter vo;	
	VideoSummary dingXi;

	int frameNumber = vc.get(CV_CAP_PROP_FRAME_COUNT);

	int ex = static_cast<int>(vc.get(CV_CAP_PROP_FOURCC));
	double fps = vc.get(CV_CAP_PROP_FPS);
	int waitTime = 10;//1000/fps;
	Size voSize(vc.get(CV_CAP_PROP_FRAME_WIDTH),vc.get(CV_CAP_PROP_FRAME_HEIGHT));
	vo.open("out.avi" , -1 , fps , voSize );
	vo.isOpened()? cout<<"opened"<<endl : cout<<"not"<<endl;
	//vc.set(CV_CAP_PROP_POS_FRAMES , 10);

	if(vc.isOpened() )
	{
		Mat src,img;
		Mat streetMask = Mat::zeros(Size(imgWidth,imgHeight), CV_8UC1);
		namedWindow("Video",0 );
		namedWindow("StreetMask",0);
		setMouseCallback("Video" , onMouse );
		createTrackbar( "pos" , "Video" , &framePos , frameNumber , playVideo );
		playVideo( framePos , 0);
		while (1)
		{	
			vc >> img;
			img.copyTo(src);
			
			//dingXi.initImg( img );
			if(img.empty() || framePos>20000 )
			{
				cout<<"over"<<endl;
				break;
			}
			else
			{
				
				Mat imgMask;
				bsm(img, imgMask,0);
				if ( np<=6 )
				{
					string mousePos = format( "(%d,%d), n=%d", mousePosition.x,mousePosition.y,np);
					putText( src , mousePos , Point(20,20) , FONT_HERSHEY_PLAIN , 1, RGB(0,255,0), 2 );
				}
				if(np==6) poly.push_back(polyPoints);
				if (np>=6)
				{
					Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
					//polylines( src , poly , true , color , 1);
					fillPoly( streetMask , poly , Scalar(255,255,255) );
					bitwise_and( streetMask , imgMask , imgMask );
				}
				dingXi.dilateIMG(imgMask,10);
				int a = dingXi.getContour(imgMask,src);
				framePos++;
				createTrackbar( "pos" , "Video" , &framePos ,frameNumber , playVideo );
				playVideo( framePos , 0);
				imshow("StreetMask",streetMask );
				imshow("Video", src);
				int key = waitKey(waitTime);
				if (key == 'i')	waitTime = 0;
				else if(key == 'k') waitTime = 1;
				else if(key == 27) break;
				if(!framePos%1000)	
					cout<<framePos<<" ";
				if(a>0)
					vo << src ;
			}
		}
		
	}
	else
	{
		printf("Cann't open video.\n");
	}
	
	return 0;
}